package com.wolfman.wolfchat.interceptor;

import cn.hutool.http.HttpStatus;
import com.wolfman.wolfchat.annotation.NeedAuthentication;
import com.wolfman.wolfchat.utils.ErrorResponseUtil;
import com.wolfman.wolfchat.utils.ThreadLocalUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @Title
 * @Description
 * @Author WolfMan
 * @Date 2022/1/15 0:41
 * @Email 2370032534@qq.com
 */
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        //如果不是映射到方法直接通过
        if (!(o instanceof HandlerMethod)) {
            return true;
        }
        //获取方法
        Method method = ((HandlerMethod) o).getMethod();
        //如果有NeedAuthentication注解，判断当前用户是否已认证，没有认证则拦截
        if (method.isAnnotationPresent(NeedAuthentication.class) && ThreadLocalUtil.getUser() == null) {
            ErrorResponseUtil.setResponse(response, "没有登录", HttpStatus.HTTP_FORBIDDEN);
            return false;
        }
        return true;
    }


}